package mskruch.gps.data;

import gpstools.data.UnsupportedFormatException;

import java.io.FileNotFoundException;

import mskruch.gps.Point;
import mskruch.gps.Points;
import mskruch.gps.Track;

@Deprecated
public class TrackLoader implements TrackLoaderAPI {
    private static final String TCX_EXTENSION = "tcx";
    private static final String GPX_EXTENSION = "gpx";
    private static final String FIT_EXTENSION = "fit";
    private TrackLoaderAPI loader;

    public TrackLoader(String fileName) throws UnsupportedFormatException, FileNotFoundException {
        String extension = resolveExtension(fileName);
        if (GPX_EXTENSION.equals(extension)) {
            loader = new GpxLoader(fileName);
        } else if (TCX_EXTENSION.equals(extension)) {
            loader = new TcxLoader(fileName);
        } else if (FIT_EXTENSION.equals(extension)) {
            loader = new FitLoader(fileName);
        } else {
            throw new UnsupportedFormatException("unknown file extension: " + extension);
        }
    }

    private String resolveExtension(String fileName) {
        return fileName.toLowerCase().substring(fileName.lastIndexOf('.') + 1);
    }

    public TrackLoader(String fileName, byte[] content) throws UnsupportedFormatException {
        String extension = resolveExtension(fileName);
        if (GPX_EXTENSION.equals(extension)) {
            loader = new GpxLoader(content);
        } else if (TCX_EXTENSION.equals(extension)) {
            loader = new TcxLoader(content);
        } else if (FIT_EXTENSION.equals(extension)) {
            loader = new FitLoader(content);
        } else {
            throw new UnsupportedFormatException("unknown file extension: " + extension);
        }
    }

    @Override
    public Track nextTrack() {
        return loader.nextTrack();
    }

    @Override
    public Track[] getTracks() {
        return loader.getTracks();
    }
    
    public Point[] getPoints() {
        Track track = loader.nextTrack();
        if (track == null){
            return null;
        }
        Points points = new Points(track.getPoints());
        while ((track = loader.nextTrack()) != null) {
            points.add(track.getPoints());
        }
        return points.toArray();
    }
}
